package com.restaurant.springboot.controller;

import com.restaurant.springboot.entity.UserEntity;
import com.restaurant.springboot.entity.dto.UserDTO;
import com.restaurant.springboot.entity.vo.TokenInfoVO;
import com.restaurant.springboot.utils.Constant;
import com.restaurant.springboot.utils.JwtUtil;
import com.restaurant.springboot.utils.RespCode;
import com.restaurant.springboot.utils.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/admin/user")
public class AdminController {
    @Autowired
    JwtUtil jwtUtil;

    @PostMapping("/login")
    public RespEntity login(@RequestBody UserDTO user, HttpSession session, HttpServletRequest request) throws Exception {
        if (user.getUsername().equals("admin") && user.getPassword().equals("111111")) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(0xC0FFEE); //因为缺少id，所以使用一个魔
            String jwt = getString(session, request, userEntity, jwtUtil);
            return new RespEntity(RespCode.SUCCESS,"login success",jwt);
        } else {
            return new RespEntity(RespCode.PASSWORDERROR);
        }
    }

    public static String getString(HttpSession session, HttpServletRequest request, UserEntity userEntity, JwtUtil jwtUtil) throws Exception {
        session.setAttribute("user",userEntity);
        String userAgent = request.getHeader("User-Agent");
        session.setAttribute("userAgent", userAgent);
        int userId = userEntity.getId();
        String subject = JwtUtil.generalSubject(userId, userAgent);
        return jwtUtil.createJWT(subject, Constant.JWT_TTL);
    }

    @GetMapping("/info")
    public RespEntity getInfo(@RequestParam String token) {
        TokenInfoVO adminTokenInfo = new TokenInfoVO();
        ArrayList<String> roles = new ArrayList<>();
        roles.add("admin");
        adminTokenInfo.setRoles(roles);
        adminTokenInfo.setIntroduction("I am a super administrator");
        adminTokenInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminTokenInfo.setName("Super Admin");
        return new RespEntity(RespCode.SUCCESS, adminTokenInfo);
    }

    @PostMapping("/logout")
    public RespEntity logout(HttpSession session) {
        session.removeAttribute("user");
        return new RespEntity(RespCode.SUCCESS);
    }

}